﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL.WxInterfaceFunc;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.DAL;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.MatrixCloudApi;

namespace Matrix.MaKaYunShang.BLL
{
    public class McAccountsBLL : BaseBLL<McAccountsBLL>
    {
        private readonly MatrixCloudCenterInterFuncBll _matrixCloudCenterInterFuncBllobj = new MatrixCloudCenterInterFuncBll();

        #region 默认方法
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(McAccounts model)
        {
            return McAccountsDAL.Instance.Add(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(McAccounts model)
        {
            return McAccountsDAL.Instance.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int Id)
        {
            return McAccountsDAL.Instance.Delete(Id);
        }
        /// <summary>
        /// 批量删除一批数据
        /// </summary>
        public bool DeleteList(string Idlist)
        {
            return McAccountsDAL.Instance.DeleteList(Idlist);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public McAccounts GetModel(int Id)
        {
            var ds = McAccountsDAL.Instance.GetModel(Id);
            return ds == null ? null : ServicesHelper.DataSetToIList<McAccounts>(ds).ToList()[0];
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<McAccounts> GetModelList(string strWhere = null)
        {
            var ds = McAccountsDAL.Instance.GetList(strWhere);
            return ServicesHelper.DataSetToIList<McAccounts>(ds).ToList();
        }
        #endregion

        #region 扩展方法

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int AddWithQrParam(McAccounts model, MatrixCloudProjectInfo projectInfo)
        {
            var resultQrCode = _matrixCloudCenterInterFuncBllobj.GetUnBindParamQrCode(projectInfo.PjMcId, projectInfo.PjSecret);

            if (resultQrCode != null && resultQrCode.Status && resultQrCode.Data != null)
            {
                model.MxWechatParamQrCodeId = resultQrCode.Data.Id;
                var result = _matrixCloudCenterInterFuncBllobj.SetBindParamQrCodeByWechatTicket(resultQrCode.Data.QrCodeTicket,
                    model.ShopId, model.MxWechatInfoUserId, projectInfo.PjMcId, projectInfo.PjSecret);

                if (!result.Status) return 0;
            }
            //model.MxWechatInfoUserId = 0;
            return McAccountsDAL.Instance.Add(model);
        }

        /// <summary>
        ///     获得分页数据列表
        /// </summary>
        public TableDataViewDto<McAccountDto> GetPagingListForShop(int draw, int pageIndex, int pageSize, string shopIds, string searchKeyWord, string colOrder, MatrixCloudProjectInfo projectInfo, bool isHeadquarters)
        {
            try
            {
                var totalCount = 0;
                var list = McAccountsDAL.Instance.GetPagingListForShop(pageIndex, pageSize, shopIds, searchKeyWord, colOrder, isHeadquarters, ref totalCount);
                if (list != null && list.Count > 0)
                {
                    var wechatUserList = new List<MxApiWechatUser>();
                    if (list.Count(l => l.MxWechatInfoUserId > 0) > 0)
                    {
                        var resultUserList =
                            _matrixCloudCenterInterFuncBllobj.GetWechatUserListByIds(
                                string.Join(",",
                                    list.DistinctBy(l => l.MxWechatInfoUserId).Select(l => l.MxWechatInfoUserId)),
                                projectInfo.PjMcId, projectInfo.PjSecret);

                        if (resultUserList.Status && resultUserList.Data != null)
                        {
                            wechatUserList = resultUserList.Data;
                        }
                    }
                    foreach (var item in list)
                    {
                        if (item.MxWechatInfoUserId > 0)
                        {
                            var wechatUser = wechatUserList.Find(l => l.WiuId == item.MxWechatInfoUserId);
                            if (wechatUser != null)
                            {
                                item.WechatUserNickName = wechatUser.NickName;
                            }
                        }
                        item.Action = "<a class='btn btn-warning' href='javascript:;' onclick=updateData(" + item.AccountId + ");>修改</a> ";
                        if (!isHeadquarters)
                        {
                            item.Action += "<a class='btn btn-danger' href='javascript:;' onclick=deleteData(" + item.AccountId + ");>删除</a>";
                        }
                    }
                }
                var returnDataList = new TableDataViewDto<McAccountDto>
                {
                    data = list,
                    draw = draw,
                    recordsFiltered = totalCount,
                    recordsTotal = totalCount
                };

                return returnDataList;
            }
            catch (Exception ex)
            {
                _fileLog.Error("McAccountsBL L| GetPagingList | Exception: " + ex);
                return null;
            }
        }


        /// <summary>
        /// 通过参数二维码ID得到一个对象实体
        /// </summary>
        public McAccounts GetModelByParamQrCodeId(int matrixParamQrCodeId, MatrixCloudProjectInfo projectInfo)
        {
            var resultQrCode = _matrixCloudCenterInterFuncBllobj.GetParamQrCodeById(matrixParamQrCodeId,
                projectInfo.PjMcId, projectInfo.PjSecret);
            if (resultQrCode.Status && resultQrCode.Data != null && resultQrCode.Data.IsBindWechatUser &&
                resultQrCode.Data.ShopId > 0)
            {
                var model = McAccountsDAL.Instance.GetModelByParamQrCodeId(matrixParamQrCodeId);
                if (model.ShopId == resultQrCode.Data.ShopId)
                {
                    return model;
                }
            }
            return null;
        }

        /// <summary>
        /// 通过accountId获取结合账户角色的账号信息实体
        /// </summary>
        /// <param name="accountId"></param>
        /// <param name="projectInfo"></param>
        /// <returns></returns>
        public McAccountDto GetModelWithRoleInfo(int accountId, MatrixCloudProjectInfo projectInfo=null)
        {
            var acccountInfo = McAccountsDAL.Instance.GetModelWithRoleInfo(accountId);
            if (acccountInfo == null || acccountInfo.AccountId == 0)
            {
                return null;
            }

            try
            {
                if (projectInfo != null)
                {
                    var resultQrCode = _matrixCloudCenterInterFuncBllobj.GetParamQrCodeById(acccountInfo.MxWechatParamQrCodeId,
                    projectInfo.PjMcId, projectInfo.PjSecret);
                    if (resultQrCode.Status)
                    {
                        acccountInfo.LocalQrCodePath = resultQrCode.Data.LocalQrCodePath;
                    }
                }
            }
            catch (Exception ex)
            {
                _fileLog.Error("McAccountsBLL | GetModelWithRoleInfo | Exception: " + ex);
                return null;
            }

            return acccountInfo;
        }

        /// <summary>
        /// 根据账号密码得到一个对象实体
        /// </summary>
        public McAccountDto GetModelByLogin(string userName, string pwd)
        {
            DataSet ds = McAccountsDAL.Instance.GetModelByLogin(userName, pwd);
            return ds == null ? null : ServicesHelper.DataSetToIList<McAccountDto>(ds).ToList().FirstOrDefault();
        }

        /// <summary>
        /// 根据店铺ID获取送店员/老板列表
        /// </summary>
        /// <param name="shopId">店铺Id</param>
        /// <param name="role">角色（1为老板，2店员）</param>
        public List<McAccountDto> GetModelListWithRoleInfoByShopId(int shopId, int role)
        {
            return McAccountsDAL.Instance.GetModelListWithRoleInfoByShopId(shopId, role);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public bool CheckUserNameAvailable(string userName, int accountId)
        {
            var ds = McAccountsDAL.Instance.GetModelByUserName(userName, accountId);
            return ds == null;
        }

        /// <summary>
        /// 根据微信用户ID获取商家后台用户数据（带权限）
        /// </summary>
        public McAccountDto GetModelWithRoleInfoByMxWechatInfoUserId(int mxWechatInfoUserId)
        {
            var ds = McAccountsDAL.Instance.GetModelWithRoleInfoByMxWechatInfoUserId(mxWechatInfoUserId);
            return ds == null ? null : ServicesHelper.DataSetToIList<McAccountDto>(ds).ToList()[0];
        }

        /// <summary>
        /// 获取店铺所有账号列表
        /// </summary>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public List<McAccounts> GetOneShopAllStaffs(int shopId)
        {
            return shopId == 0 ? GetModelList() : GetModelList(" ShopId = " + shopId + " and AccountType<>1");
        }

        /// <summary>
        /// 根据店铺ID批量删除一批数据
        /// </summary>
        /// <remarks>2016-07-21 万乐园 创建</remarks>
        public bool DeleteListByShopIds(string shopIds)
        {
            return McAccountsDAL.Instance.DeleteListByShopIds(shopIds);
        }

        public McAccounts GetModelByMxWechatInfoUserId(int wiuId)
        {
            var ds = McAccountsDAL.Instance.GetModelByMxWechatInfoUserId(wiuId);
            return ds == null ? null : ServicesHelper.DataSetToIList<McAccounts>(ds).ToList()[0];
        }
        #endregion
    }
}